<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>localStorage</title>
    <script type="text/javascript">
        function $(id) {
            return document.getElementById(id);
        }

        function setItem () {
            let key = $('key').value;
            let value = $('value').value;

            localStorage.setItem(key, value);
            refreshDiv();
        }

        function getItem () {
            let key = $('key').value;
            alert(localStorage.getItem(key));
        }

        function removeItem () {
            let key = $('key').value;
            localStorage.removeItem(key);
            refreshDiv();
        }

        function doClear () {
            localStorage.clear();
            refreshDiv();
        }

        function getKey () {
            alert(`the 1st key is : ${localStorage.key(0)}`);
            // localStorage.key
        }

        function getLength () {
            alert(`the Length is : ${localStorage.length}`);
        }

        // 这个方法只有IE支持（不建议使用）
        function getRemainSpace () {
            alert(`the remain space is: ${localStorage.remainingSpace}`);
        }

        function refreshDiv () {
            let res = ['localStorage.length: ' + localStorage.length];
            for (let i = localStorage.length; i--; ) {
                var key = localStorage.key(i);
                res.push(`${key}: ${localStorage.getItem(key)}`);
            }
            $('showDiv').innerHTML = res.join('<br/>');
        }
        

        window.onload = function () {
            refreshDiv();
        }
    </script>
</head>
<body>
    <label for="">Key:<input id="key" type="text" value="">&nbsp;&nbsp;&nbsp;&nbsp;</label><br />
    <label for="">value:<input id="value" type="text" value="">&nbsp;&nbsp;&nbsp;&nbsp;</label><br />
    <button onclick="setItem()">setItem</button><br />
    <button onclick="getItem()">getItem</button><br />
    <button onclick="removeItem()">removeItem</button><br />
    <!-- 不可以命名为clear()函数，因为button有自己的clear()函数 -->
    <button onclick="doClear()">clear</button><br />
    <button onclick="getKey()">key(0)</button><br />
    <button onclick="getLength()">length</button><br />
    <!-- 只用IE支持 -->
    <button onclick="getRemainSpace()">remainSpace</button>
    <div id="showDiv" style="border: 1px solid #ff0000; width: 400px; height: 500px;"></div>
</body>
</html>